package com.ltmonitor.web.controller.websocket;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.socket.TextMessage;

import com.ltmonitor.entity.UserInfo;
 
@Controller
@RequestMapping("/msg")
public class MsgController {
 
    //@Resource
    MyWebSocketHandler handler;
 
    Map<Long, UserInfo> users = new HashMap<Long, UserInfo>();
    
    @RequestMapping(value ="",method=RequestMethod.GET)
	@ResponseBody
	public ModelAndView addarticle(HttpServletRequest req, HttpServletResponse resp) {
		ModelAndView mv = new ModelAndView();
		mv.setViewName("msg/index");

		return mv;
	}
    
         
        //模拟一些数据
    @ModelAttribute
    public void setReqAndRes() {
        UserInfo u1 = new UserInfo();
        u1.setEntityId(1L);
        u1.setName("张三");
        users.put(u1.getEntityId(), u1);
 
        UserInfo u2 = new UserInfo();
        u2.setEntityId(2L);
        u2.setName("李四");
        users.put(u2.getEntityId(), u2);
 
    }
     
    //用户登录
    @RequestMapping(value="login",method=RequestMethod.POST)
    public ModelAndView doLogin(UserInfo user,HttpServletRequest request){
        request.getSession().setAttribute("uid", user.getEntityId());
        request.getSession().setAttribute("name", users.get(user.getEntityId()).getName());
        return new ModelAndView("redirect:talk");
    }
     
    //跳转到交谈聊天页面
    @RequestMapping(value="talk",method=RequestMethod.GET)
    public ModelAndView talk(){
        return new ModelAndView("talk");
    }
    //跳转到发布广播页面
    @RequestMapping(value="broadcast",method=RequestMethod.GET)
    public ModelAndView broadcast(){
        return new ModelAndView("broadcast");
    }
     
    //发布系统广播（群发）
    @ResponseBody
    @RequestMapping(value="broadcast",method=RequestMethod.POST)
    public void broadcast(String text) throws IOException{
        Message msg=new Message();
        msg.setDate(new Date());
        msg.setFrom(-1L);
        msg.setFromName("系统广播");
        msg.setTo(0L);
        msg.setText(text);
        JSONObject j = JSONObject.fromObject(msg);
        handler.broadcast(new TextMessage(j.toString()));
    }
 
}